package com.founder.devwork.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.founder.devwork.dto.res.EmailEntry;
import com.founder.devwork.dto.res.EngineerDTO;
import com.founder.devwork.entity.Department;
import com.founder.devwork.entity.Engineer;
import com.founder.devwork.entity.EngineerEmail;
import com.founder.devwork.persistence.mapper.DepartmentMapper;
import com.founder.devwork.service.DepartmentService;
import com.founder.devwork.service.EngineerEmailService;
import com.founder.devwork.service.EngineerService;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * DepartmentServiceImpl 用于实现 DepartmentService 接口。
 * 提供查询部门信息的方法。
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Autowired
    private EngineerService engineerService;

    @Autowired
    private EngineerEmailService engineerEmailService;

    /**
     * @inheritDoc
     */
    @Override
    public Set<EngineerDTO> getAllEngineersByDeptId(String deptId) {
        Set<String> deptIds = new HashSet<>();
        deptIds.add(deptId);
        collectChildDeptIds(deptId, deptIds);

        List<Engineer> engineers = engineerService.lambdaQuery().in(Engineer::getDeptId, deptIds).list();

        // Fetch all related emails
        List<EngineerEmail> emails = engineerEmailService
            .lambdaQuery()
            .in(EngineerEmail::getEngineerId, engineers.stream().map(Engineer::getId).collect(Collectors.toSet()))
            .list();

        // Group emails by engineerId
        Map<String, List<EmailEntry>> emailMap = emails
            .stream()
            .collect(Collectors.groupingBy(ee -> ee.getEngineerId(), Collectors.mapping(ee -> new EmailEntry(ee.getAuthorFullname(), ee.getAuthorEmail()), Collectors.toList())));

        // Create DTOs
        return engineers
            .stream()
            .map(eng -> {
                EngineerDTO dto = new EngineerDTO(eng.getId(), eng.getName(), eng.getRole(), eng.getDeptId(), emailMap.getOrDefault(eng.getId(), Collections.emptyList()));
                return dto;
            })
            .collect(Collectors.toSet());
    }

    /**
     * 收集子部门ID
     *
     * @param parentId 父部门ID
     * @param deptIds 子部门ID集合
     */
    private void collectChildDeptIds(String parentId, Set<String> deptIds) {
        List<Department> children = this.lambdaQuery().eq(Department::getParentId, parentId).list();
        for (Department child : children) {
            deptIds.add(child.getId());
            collectChildDeptIds(child.getId(), deptIds);
        }
    }
}
